#include <iostream>
#include <cmath>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>

#include "SharedMemoryBuffer.h"

int main(int argc, char* argv[]) {
	try 
	{
		boost::interprocess::shared_memory_object shm(
			boost::interprocess::open_only, // dont create new shm
			"shared_memory",
			boost::interprocess::read_write
		);
		shm.truncate(sizeof(SharedMemoryBuffer));

		boost::interprocess::mapped_region region(
			shm,
			boost::interprocess::read_write
		);

		void* regionAddr = region.get_address();

		// obtain the created buffer from memory
		SharedMemoryBuffer* buffer = static_cast<SharedMemoryBuffer*>(regionAddr);

		while(true)
		{
			// only proceed execution if first process has written to buffer
			// make writing to the buffer mutually exclusice
			buffer->reader.wait();
			std::cout << "calculating sqrt from buffer value: " << buffer->data << std::endl;
			buffer->data = sqrt(buffer->data);
			sleep(1);
			// allow the writer to reader sqrt and write new data
			buffer->writer.post();
		}
	}
	catch(boost::interprocess::interprocess_exception &e)
	{
		boost::interprocess::shared_memory_object::remove("shared_memory");
		std::cerr << "error occured: " << e.what();
		return 1;
	}
	boost::interprocess::shared_memory_object::remove("shared_memory");
	return 0;
}